import { GlobalHelp, DynamicInstanceConfig } from "@ibiz/dynamic-model-api";
import { AppServiceBase, AppModelService, Http, Util } from "ibiz-core";
import { AppCenterService, AppViewShell, AppIndexViewShell } from "ibiz-vue";
import { Environment } from "@/environments/environment";
import i18n from "@/locale";
import { handleLocaleMap } from "@/locale/local-util";

export class AuthGuardBase {
  /**
   * @description 初始化应用服务
   * @param {*} router
   * @return {*}  {Promise<void>}
   * @memberof PreviewUtil
   */
  async initAppService(router: any): Promise<void> {
    AppServiceBase.getInstance().setAppEnvironment(Environment);
    AppServiceBase.getInstance().setAppStore(router.app.$store);
    AppServiceBase.getInstance().setI18n(i18n);
    AppServiceBase.getInstance().setRouter(router);
    const service = new AppModelService();
    await GlobalHelp.install(service, async (strPath: string, config: DynamicInstanceConfig) => {
      try {
        const result: any = await Http.getInstance().post('/getModel', { path: strPath });
        return result.data ? result.data : null;
      } catch (error) {
        return null;
      }
    }, { lang: Environment?.isEnableMultiLan ? handleLocaleMap(i18n.locale) : '' });
    AppServiceBase.getInstance().setAppModelDataObject(service.app);
    AppCenterService.getInstance(router.app.$store);
    await this.fillEntityModel();
    await this.initRouter(router);
  }

  /**
   * @description 填充实体模型
   * @memberof PreviewUtil
   */
  private async fillEntityModel() {
    const entities = AppServiceBase.getInstance().getAppModelDataObject().getAllPSAppDataEntities() || [];
    for (let i = 0; i < entities.length; i++) {
      const entity = entities[i];
      if (!entity.isFill) {
        await entity.fill();
      }
    }
  }

  /**
   * @description 初始化路由
   * @private
   * @param {*} router
   * @memberof PreviewUtil
   */
  private initRouter(router: any) {
    const app = AppServiceBase.getInstance().getAppModelDataObject();
    const entities = app.getAllPSAppDataEntities() || [];
    //  player下路由
    for (let j = 0; j < entities.length; j++) {
      const { codeName } = entities[j];
      const route: any = {
        path: `${Util.srfpluralize(codeName).toLowerCase()}/:${codeName.toLowerCase()}?/views/:view?`,
        meta: {
          captionTag: '',
          caption: '',
          info: '',
          imgPath: '',
          iconCls: '',
          parameters: [
            { pathName: 'player', parameterName: 'player' },
            { pathName: Util.srfpluralize(codeName).toLowerCase(), parameterName: codeName.toLowerCase() },
            { pathName: 'views', parameterName: 'view' },
          ],
          resource: codeName.toLowerCase(),
          requireAuth: false,
        },
        component: AppViewShell
      }
      router.addRoute('player', route);
    }
    //  首页视图路由
    const indexViews = ((app.M as any).cache?.getPSAppViews || []).filter((view: any) => view.viewType == 'APPINDEXVIEW');
    if (indexViews.length > 0) {
      indexViews.forEach((index: any) => {
        const indexCodeName = index.codeName?.toLowerCase();
        const route1: any = {
          path: `/player/views/${indexCodeName}`,
          meta: {
            captionTag: '',
            caption: '',
            info: '',
            imgPath: '',
            iconCls: '',
            viewType: 'APPINDEX',
            parameters: [
              { pathName: 'views', parameterName: 'player' },
            ],
            ignoreIndex: true,
            dynaModelFilePath: index.dynaModelFilePath,
            requireAuth: false,
          },
          component: AppIndexViewShell,
        }
        router.addRoute('player', route1);
      })
    }
  }
}